package com.lynx.core.impl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.lynx.core.View;
import com.lynx.core.type.Encoding;
/**
 * 
 * @author lxp
 *
 */
public class JsonView implements View {
	private String ENCODING = Encoding.utf_8.getCode();
	private Object obj;
	private String val;

	public JsonView(Object obj) {
		this.obj = obj;
	}

	public JsonView(Object obj, Encoding encoding) {
		this.obj = obj;
		this.ENCODING = encoding.getCode();
	}

	public JsonView(String val) {
		this.val = val;
	}
	public JsonView(String val, Encoding encoding) {
		this.val = val;
		this.ENCODING = encoding.getCode();
	}

	public Object getObj() {
		return this.obj;
	}

	public String getVal() {
		return this.val;
	}

	public void render(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException,Exception {
		if (this.obj != null) {
			response.setCharacterEncoding(ENCODING);
			response.setHeader("Content-Type", "application/json; charset="
					+ ENCODING);
			PrintWriter writer = response.getWriter();
			try {
				if (obj!=null) {
					writer.print(new Gson().toJson(obj));	
				}else{
					writer.print(val);
				}
				
			} finally {
				writer.close();
			}
		}
	}
}
